package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis plus相关配置
 *
 * @author alex
 * @date 2020/06/03
 */
@Slf4j
@Configuration
@MapperScan("com.ruoyi.system.mapper")
public class MyBatisPlusConfig implements MetaObjectHandler {

    /**
     * 新增数据默认字段填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser user = SecurityUtils.getLoginUser();
        if (user != null) {
            this.strictInsertFill(metaObject, "createBy", String.class, user.getUsername());
            this.strictInsertFill(metaObject, "updateBy", String.class, user.getUsername());
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    /**
     * 更新数据默认字段填充策略
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 强制更新
        setFieldValByName("updateTime", LocalDateTime.now(), metaObject);

        LoginUser user = SecurityUtils.getLoginUser();
        if (user != null) {
            setFieldValByName("updateBy", user.getUsername(), metaObject);
        }
    }
}
